package com.sanerzone.smscenter.gateway.http.handler.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sanerzone.smscenter.biz.message.*;
import com.sanerzone.smscenter.common.tools.HttpRequest;
import com.sanerzone.smscenter.gateway.http.handler.GateWayHttpAbstract;
import com.sanerzone.smscenter.gateway.http.message.SmsHttpMsgResponse;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class SmsApiNAHANNEWV3
  extends GateWayHttpAbstract
{
  public SmsApiNAHANNEWV3(String gateWayID, String jsonParams)
  {
    super(gateWayID, jsonParams);
  }
  
  public List<SMSSRMessage> doSend(SMSMTMessage mt)
  {
    Map<String, Object> params = Maps.newHashMap();
    try
    {
      String t = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
      params.put("SpCode", this.paramsMaps.get("SpCode"));
      params.put("LoginName", this.paramsMaps.get("LoginName"));
      params.put("Password", this.paramsMaps.get("password"));
      params.put("MessageContent", URLEncoder.encode(mt.getSmsContent(), "utf-8"));
      params.put("UserNumber", mt.getPhone());
      params.put("SerialNumber", mt.getId());
      params.put("ScheduleTime", t);
      params.put("f", this.paramsMaps.get("f"));
    }
    catch (UnsupportedEncodingException e)
    {
      this.logger.error("网关:{}, 响应:{}", this.gateWayID, e);
    }
//    String json = HttpRequest.sendGet((String)this.paramsMaps.get("apiUrl") + "/sms/Api/Send.do", Joiner.on("&").withKeyValueSeparator("=").join(params), null);
    String json = HttpRequest.sendFormPost((String)this.paramsMaps.get("apiUrl") + "/sms/Api/Send.do", Joiner.on("&").withKeyValueSeparator("=").join(params), null, "UTF-8", 3000);
    this.logger.info("网关:{}, 请求:{}, 响应:{}", new Object[] { this.gateWayID, params.toString(), json });
    
    List<SMSSRMessage> resultList = Lists.newArrayList();
    
    SMSSRMessage message = initGatewayResultMessage(json, mt, "result");
    String resultCode = null;
    String resultMessage = null;
    String taskid = null;
    if (StringUtils.equals(message.getResult(), "F10199"))
    {
      Map<String, String> map = Splitter.on("&").withKeyValueSeparator("=").split(json);
      resultCode = String.valueOf(map.get("result"));
      resultMessage = String.valueOf(map.get("description"));
      if (StringUtils.equals(resultCode, "0")) {
        taskid = String.valueOf(map.get("taskid"));
      }
      message.setMsgkey(mt.getPhone());
      setGatewayResultCode(message, taskid, resultCode, resultMessage, "0");
    }
    resultList.add(message);
    return resultList;
  }
  
  public SmsHttpMsgResponse parseReport(String text, List<SMSRTMessage> rtList)
  {
    this.logger.info("{}网关推送状态报告:{}", this.gateWayID, text);
    Map<String, String> map = Splitter.on("&").withKeyValueSeparator("=").split(text);
    if ((StringUtils.equals("0", (CharSequence)map.get("result"))) && (StringUtils.isNotBlank((CharSequence)map.get("out"))))
    {
      String[] datas = ((String)map.get("out")).split(";");
      for (int i = 0; i < datas.length; i++)
      {
        String[] data = datas[i].split(",");
        SMSRTMessage smsRtMessage = initSmsRtMessage(data[0], data[1], data[1], data[2], "0");
        
        rtList.add(smsRtMessage);
      }
    }
    return new SmsHttpMsgResponse("ok");
  }
  
  public SmsHttpMsgResponse parseDeliver(String text, List<SMSMOMessage> moList)
  {
    this.logger.info("{}网关推送用户上行:{}", this.gateWayID, text);
    String id = "";
    Map<String, String> map = Splitter.on("&").withKeyValueSeparator("=").split(text);
    if ((StringUtils.equals("0", (CharSequence)map.get("result"))) && (StringUtils.isNotBlank((CharSequence)map.get("replys"))))
    {
      JSONArray datas = JSON.parseArray((String)map.get("replys"));
      for (int i = 0; i < datas.size(); i++)
      {
        JSONObject data = datas.getJSONObject(i);
        SMSMOMessage sMSMOMessage = new SMSMOMessage();
        sMSMOMessage.setGateWayID(this.gateWayID);
        sMSMOMessage.setMsgContent(data.getString("content"));
        sMSMOMessage.setMsgid(data.getString("id"));
        sMSMOMessage.setPhone(data.getString("mdn"));
        sMSMOMessage.setSpnumber(data.getString("callmdn"));
        sMSMOMessage.setUuid(UUID.randomUUID().toString());
        moList.add(sMSMOMessage);
        id = data.getString("id");
      }
    }
    Map<String, String> params = Maps.newHashMap();
    params.put("SpCode", this.paramsMaps.get("SpCode"));
    params.put("LoginName", this.paramsMaps.get("LoginName"));
    params.put("password", this.paramsMaps.get("password"));
    params.put("id", id);
    HttpRequest.sendPost((String)this.paramsMaps.get("apiUrl") + "/sms/Api/replyConfirm.do", Joiner.on("&").withKeyValueSeparator("=").join(params), null);
    return null;
  }
  
  public String queryReport(String jsonText)
  {
    Map<String, String> params = Maps.newHashMap();
    params.put("SpCode", this.paramsMaps.get("SpCode"));
    params.put("LoginName", this.paramsMaps.get("LoginName"));
    params.put("Password", this.paramsMaps.get("password"));
    String json = HttpRequest.sendPost((String)this.paramsMaps.get("apiUrl") + "/sms/Api/report.do", Joiner.on("&").withKeyValueSeparator("=").join(params), null);
//    logger.info("通道：{}，主动查询异步状态结果：{}", this.gateWayID, json);
    return json;
  }
  
  public String queryDeliver(String jsonText)
  {
    Map<String, String> params = Maps.newHashMap();
    params.put("SpCode", this.paramsMaps.get("SpCode"));
    params.put("LoginName", this.paramsMaps.get("LoginName"));
    params.put("Password", this.paramsMaps.get("password"));
    String json = HttpRequest.sendFormPost((String)this.paramsMaps.get("apiUrl") + "/sms/Api/report.do", Joiner.on("&").withKeyValueSeparator("=").join(params), null, "UTF-8", 3000);
//    logger.info("通道：{}，主动查询上行结果：{}", this.gateWayID, json);
    return json;
  }
  
  public String balance()
  {
    Map<String, String> params = Maps.newHashMap();
    params.put("SpCode", this.paramsMaps.get("SpCode"));
    params.put("LoginName", this.paramsMaps.get("LoginName"));
    params.put("Password", this.paramsMaps.get("password"));
    String apiUrl = (String)this.paramsMaps.get("apiUrl") + "/sms/Api/searchNumber.do";
    String param = Joiner.on("&").withKeyValueSeparator("=").join(params);
    System.out.println("apiUrl=" + apiUrl + ",param=" + param);
    String result = HttpRequest.sendFormPost((String)this.paramsMaps.get("apiUrl") + "/sms/Api/searchNumber.do", Joiner.on("&").withKeyValueSeparator("=").join(params), null, "UTF-8", 3000);
    this.logger.info("余额查询网关:{}, 请求:{}, 响应:{}", new Object[] { this.gateWayID, params.toString(), result });
    JSONObject object = JSON.parseObject(result);
    if (StringUtils.equals("0", object.getString("result"))) {
      return "余额：" + object.getString("result");
    }
    return "余额查询失败";
  }
  
  public static void main(String[] args)
  {
    String params = "{\"SpCode\":\"1010\",\"LoginName\":\"yuanheng\",\"password\":\"yuanheng\",\"apiUrl\":\"http://47.100.127.72:8513/\",\"f\":\"1\"}";
    SmsApiNAHANNEWV3 api = new SmsApiNAHANNEWV3("ZY", params);
api.balance();
//    api.send(api);
//    api.queryReport("");
  }



  public void send(SmsApiNAHANNEWV3 api)
  {
    SMSMTMessage mt = new SMSMTMessage();
    SMSREQMessage sm = new SMSREQMessage();
    sm.setTaskid("123456789");
    mt.setSmsREQMessage(sm);
    mt.setPhone("18368493887");
    mt.setSmsContent("【千橡科技】验证码：123456，10分钟内有效，如非本人操作，请忽略！");
    api.doSend(mt);
  }
}
